package com.boco.modules.fdoc.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import redis.clients.jedis.Jedis;
import sun.misc.BASE64Decoder;

import com.boco.common.jedis.JedisUtils;
import com.boco.common.json.BaseJsonVo;
import com.boco.common.utils.JsonUtils;
import com.boco.common.utils.StringUtils;
import com.boco.common.web.BaseController;
import com.boco.modules.fdoc.model.UserDocSignEntity;
import com.boco.modules.fdoc.model.UserRelationsEntity;
import com.boco.modules.fdoc.service.ResidentService;
import com.boco.modules.fdoc.service.SigServicepackService;
import com.boco.modules.fdoc.service.SignService;
import com.boco.modules.fdoc.service.UserService;
import com.boco.modules.fdoc.vo.ResidentVo;
import com.boco.modules.fdoc.vo.SignVo;
import com.boco.modules.fdoc.vo.UserVo;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wordnik.swagger.annotations.ApiOperation;

/**
 * 家庭医生签约API
 * 
 * @author q
 *
 */

@RestController
@RequestMapping(value = "/sign", produces = "text/json;charset=UTF-8")
public class SignApi extends BaseController {

	@Resource
	SignService signService;
	@Resource
	UserService userService;
	@Resource
	ResidentService residentService;
	@Resource
	SigServicepackService sigServicepackService;

	@RequestMapping(value = "/getSignNum", method = RequestMethod.GET)
	@ApiOperation(value = "获取该医生区域已签约的人数和未签约的人数、百分比", notes = "{'uid':'当前登录医生ID'}", response = SignVo.class)
	public String getSignNum(@RequestParam String uid) {
		SignVo vo = signService.getSignNum(uid);
		return JsonUtils.getJson(BaseJsonVo.success(vo))             ;
	}

	@RequestMapping(value = "/getHasSignedList", method = RequestMethod.GET)
	@ApiOperation(value = "获取该医生区域已签约人员列表", notes = "{'uid':'当前登录医生ID'}", response = UserRelationsEntity.class)
	public String getHasSignedList(@RequestParam String uid) {     
		List<ResidentVo> list = signService.getSignedList(uid);
		return JsonUtils.getJson(BaseJsonVo.success(list));       
	}

	@RequestMapping(value = "/getHasnotSignedList", method = RequestMethod.GET)
	@ApiOperation(value = "获取该医生区域未签约人员列表", notes = "{'uid':'当前登录医生ID'}", response = UserRelationsEntity.class)
	public String getHasnotSignedList(@RequestParam String uid) {
		Jedis jedis = JedisUtils.getResource();
        String regionList = jedis.get(uid + "regionList");  
        System.out.println(regionList);  
        
		List<ResidentVo> list = signService.getNotSignedList(uid);
		return JsonUtils.getJson(BaseJsonVo.success(list));
	}

	@RequestMapping(value = "/sign", method = RequestMethod.POST)
	@ApiOperation(value = "签约", notes = "{'docUid':'医生UID','data':[{'idCard':'就诊人身份证','headImg':'图片base64字符串','strName':'图片名','sigId':'所选服务包ID'}]}")
	public String sign(@RequestBody String signBody, HttpServletRequest request) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
		mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		try {
			HashMap jsonMap = mapper.readValue(signBody, HashMap.class);
			String uid = String.valueOf(jsonMap.get("docUid"));
			ArrayList<HashMap<String, String>> list = (ArrayList) jsonMap
					.get("data");

			for (HashMap<String, String> hashMap : list) {
				UserDocSignEntity en = new UserDocSignEntity();

				String idCard = hashMap.get("idCard"); // 获取当前数组的就诊人ID
				String sigId = hashMap.get("sigId");
				String headImg = hashMap.get("headImg"); // 获取当前数组的图片base64字符串
				String strName = hashMap.get("strName"); // 获取当前数组的图片名
				/**
				 * 图片上传部分
				 */
				if (headImg != null && !"".equals(headImg)) {
					String path = request.getSession().getServletContext()
							.getRealPath("upload/img")
							+ "\\";
					BASE64Decoder decoder = new BASE64Decoder();
					// Base64解码
					byte[] b = decoder.decodeBuffer(headImg);
					for (int i = 0; i < b.length; ++i) {
						if (b[i] < 0) {// 调整异常数据
							b[i] += 256;
						}
					}
					// 生成jpeg图片
					String headSuffix = StringUtils.getSuffix(strName); // 获取后缀名
					String signImgHeadName = UUID.randomUUID().toString()
							.substring(0, 8)
							+ "." + headSuffix; // 重命名为8位随机数
					String localPathHead = path + signImgHeadName;
					File headPathHead = new File(path);// 获取文件夹路径
					if (!headPathHead.exists()) {// 判断文件夹是否创建，没有创建则创建新文件夹
						headPathHead.mkdirs();
					}

					OutputStream out = new FileOutputStream(localPathHead);
					out.write(b);
					out.flush();
					out.close();
					en.setSignImgHead((request.getContextPath() + "/upload/img/"
							+ signImgHeadName).substring(9));
				}
				/**
				 * 设置持久化对象信息
				 */
				en.setDocUid(uid);
				en.setIdCard(idCard);
				en.setSigId(Integer.parseInt(sigId));
				signService.sign(en);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JsonUtils.getJson(BaseJsonVo.success(null));
	}

	@RequestMapping(value = "/getNotSignedListByRelation", method = RequestMethod.GET)
	@ApiOperation(value = "通过签约人身份证查询该家庭尚未签约的人员", notes = "{'idCard':'签约人身份证'}", response = UserRelationsEntity.class)
	public String getNotSignedListByRelation(@RequestParam String idCard) {
		ResidentVo residentMaster = residentService.getResidentMaster(idCard);
		List<ResidentVo> list = signService
				.getRelationsNotSigned(residentMaster.getIdCard());
		return JsonUtils.getJson(BaseJsonVo.success(list));
	}

	@RequestMapping(value = "/isSigned", method = RequestMethod.GET)
	@ApiOperation(value = "查看当前登录人是否有签约的医生（用户端）", notes = "{'uid':'当前登录用户uid'}")
	public String isSigned(@RequestParam String uid) {
		return JsonUtils.getJson(BaseJsonVo.success(signService.isSigned(uid)));
	}
	
	@RequestMapping(value = "/getSignDetail", method = RequestMethod.GET)
	@ApiOperation(value = "查看当前登录人的签约详情（用户端）", notes = "{'uid':'当前登录用户uid'}")
	public String getSignDetail(@RequestParam String uid) {
		return JsonUtils.getJson(BaseJsonVo.success(signService.getSignDetail(uid)));
	}
	
	@RequestMapping(value = "/getServicePacks", method = RequestMethod.GET)
	@ApiOperation(value = "查询所有服务包")
	public String getServicePacks() {
		return JsonUtils.getJson(BaseJsonVo.success(sigServicepackService.getAll()));
	}
	
	@RequestMapping(value = "/getServicePackDetails", method = RequestMethod.GET)
	@ApiOperation(value = "查询服务包详细信息",notes = "{'servicepackId':'服务包ID，为0时查询所有服务包'}")
	public String getServicePackDetails(@RequestParam Integer servicepackId) {
		if (servicepackId == null || servicepackId == 0) {
			return JsonUtils.getJson(BaseJsonVo.success(sigServicepackService.getAllDetails()));
		}else {
			return JsonUtils.getJson(BaseJsonVo.success(sigServicepackService.getServicePackDetailsListNotPage(servicepackId)));
		}
	}
	
}
